package com.zzt.spider.service.searchService;

import com.zzt.spider.enums.SpiderSourceEnum;
import com.zzt.spider.model.entity.SpiderSource;
import com.zzt.spider.service.SpiderSourceService;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class FreeKanPianSourceGCService {
    private static final Logger log = LoggerFactory.getLogger(FreeKanPianSourceGCService.class);
    private static final int MAX_RETRIES = 3;
    private static final Duration DEFAULT_WAIT = Duration.ofSeconds(15L);
    @Autowired
    private SpiderSourceService spiderSourceService;

    public void getSource() {
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments(new String[]{"--remote-allow-origins=*", "--headless", "--disable-gpu", "--no-sandbox", "--disable-dev-shm-usage"});
        List<SpiderSource> sources = new ArrayList();
        ChromeDriver driver = null;
        List<String> htmlList = new ArrayList();

        try {
            for(int page = 1; page <= 5; ++page) {
                String baseUrl = page == 1 ? "https://www.freekanpian.com/category/2437.html" : "https://www.freekanpian.com/category/2437/time-" + page + ".html";

                try {
                    driver = new ChromeDriver(options);
                    driver.get(baseUrl);
                    WebDriverWait wait = new WebDriverWait(driver, DEFAULT_WAIT);
                    List<WebElement> links = (List)wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector(".col-lg-wide-75.col-xs-1.padding-0 li.col-md-6.col-sm-4.col-xs-3 a[href]")));
                    int maxLinks = links.size();

                    for(int i = 0; i < maxLinks; ++i) {
                        int retry = 0;

                        while(retry < 3) {
                            try {
                                List<WebElement> currentLinks = driver.findElements(By.cssSelector(".col-lg-wide-75.col-xs-1.padding-0 li.col-md-6.col-sm-4.col-xs-3 a[href]"));
                                if (currentLinks.size() <= i) {
                                    log.info("⚠️ 链接数量不足");
                                } else {
                                    WebElement link = (WebElement)currentLinks.get(i);
                                    String href = link.getAttribute("href");
                                    if (!htmlList.contains(href)) {
                                        htmlList.add(href);
                                    }
                                }
                                break;
                            } catch (StaleElementReferenceException var21) {
                                log.info("\ud83d\udd04 元素过期，重试中... (" + (retry + 1) + "/3)");
                                if (retry == 2) {
                                    log.info("❌ 达到最大重试次数，跳过此链接");
                                }

                                ++retry;
                            } catch (Exception var22) {
                                System.err.println("处理链接时出错: " + var22.getMessage());
                                break;
                            }
                        }
                    }
                } catch (Exception var23) {
                    System.err.println("主程序出错: " + var23.getMessage());
                    var23.printStackTrace();
                } finally {
                    this.quit(driver);
                }

                Iterator var26 = htmlList.iterator();

                while(var26.hasNext()) {
                    String htmlHref = (String)var26.next();
                    SpiderSource spiderSource = new SpiderSource();
                    spiderSource.setUrl(htmlHref);
                    spiderSource.setFrom(SpiderSourceEnum.FREEKANPIANGC.getFrom());
                    spiderSource.setState(0);
                    spiderSource.setUpdateTime(LocalDateTime.now());
                    spiderSource.setLocation("国产");
                    sources.add(spiderSource);
                }

                this.save(sources);
            }
        } catch (Exception var25) {
            System.err.println("主程序出错: " + var25.getMessage());
            var25.printStackTrace();
        }

    }

    private void save(List<SpiderSource> sources) {
        if (sources != null && !sources.isEmpty()) {
            Iterator var2 = sources.iterator();

            while(var2.hasNext()) {
                SpiderSource source = (SpiderSource)var2.next();
                this.spiderSourceService.saveSource(source);
            }

        }
    }

    private void quit(ChromeDriver driver) {
        try {
            if (driver != null) {
                driver.quit();
                log.info("✅ ChromeDriver 已正常关闭");
            }
        } catch (Exception var4) {
            log.error("❌ ChromeDriver 关闭失败: " + var4.getMessage());
        }

        try {
            Runtime.getRuntime().exec("bash -c \"ps aux | grep '/mnt/spider/chrome-linux64/chrome' | grep -v grep | awk '{print $2}' | xargs -r kill -9\"");
            Runtime.getRuntime().exec("bash -c \"ps aux | grep 'chromedriver' | grep -v grep | awk '{print $2}' | xargs -r kill -9\"");
        } catch (IOException var3) {
            log.error("杀chrome失败: " + var3.getMessage());
        }

    }
}
